package com.liesheng.haylou.service;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.IBinder;

import com.liesheng.daemonlib.service.AbsWorkService;
import com.liesheng.haylou.app.HyApplication;
import com.liesheng.haylou.bluetooth.BleDataInfo;
import com.liesheng.haylou.bluetooth.BleManager;
import com.liesheng.haylou.bluetooth.ScanRecordUtil;
import com.liesheng.haylou.event.DialogCloseEvent;
import com.liesheng.haylou.ui.device.SearchDeviceActivity;
import com.liesheng.haylou.ui.main.DialogActivity;
import com.liesheng.haylou.utils.LogUtil;
import com.liesheng.haylou.utils.NumUtil;

import org.greenrobot.eventbus.EventBus;

import java.util.concurrent.TimeUnit;

import rx.Observable;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;


/**
 * Date:2019/11/18
 * <p>
 * Author:wuzhiguang
 * <p>
 * Description:
 * 应用退到后台时该服务开始工作，后台扫描蓝牙设备，如果扫描到了相关设备则弹框
 */
public class TraceServiceImpl extends AbsWorkService {

    //是否 任务完成, 不再需要服务运行?
    public static boolean sShouldStopService;
    public static Subscription subscription;


    public static void stopService() {
        //我们现在不再需要服务运行了, 将标志位置为 true
        sShouldStopService = true;
        //取消对任务的订阅
        if (subscription != null) subscription.unsubscribe();
        //取消 Job / Alarm / Subscription
        cancelJobAlarmSub();

    }

    /**
     * 是否 任务完成, 不再需要服务运行?
     *
     * @return 应当停止服务, true; 应当启动服务, false; 无法判断, 什么也不做, null.
     */
    @Override
    public Boolean shouldStopService(Intent intent, int flags, int startId) {
        return sShouldStopService;
    }

    @Override
    public void startWork(Intent intent, int flags, int startId) {
        LogUtil.d("TraceServiceImpl  --- startWork");
        subscription = Observable
                .interval(0, BleManager.SCAN_DURING + 10 * 1000, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<Long>() {
                    @Override
                    public void call(Long aLong) {
                        BleManager.getInstance().scanBle(leScanCallback);
                    }
                });
    }

    private BluetoothAdapter.LeScanCallback leScanCallback = new BluetoothAdapter.LeScanCallback() {
        @Override
        public void onLeScan(BluetoothDevice bluetoothDevice, int i, byte[] bytes) {

            BleDataInfo info = BleDataInfo.create(bytes, null);

            if (info.isShowBleDialog() && !HyApplication.mApp.isForeground(DialogActivity.class)) {
                DialogActivity.startBy(TraceServiceImpl.this, bluetoothDevice, info.getLeftAddress(), info.getRightAddress(),info.getAdCount());
            } else {
                info.checkShouldCloseBleDialog();
            }

        }
    };

    @Override
    public void stopWork(Intent intent, int flags, int startId) {
        stopService();
    }

    /**
     * 任务是否正在运行?
     *
     * @return 任务正在运行, true; 任务当前不在运行, false; 无法判断, 什么也不做, null.
     */
    @Override
    public Boolean isWorkRunning(Intent intent, int flags, int startId) {
        //若还没有取消订阅, 就说明任务仍在运行.
        return subscription != null && !subscription.isUnsubscribed();
    }

    @Override
    public IBinder onBind(Intent intent, Void v) {
        return null;
    }

    @Override
    public void onServiceKilled(Intent rootIntent) {
        LogUtil.d("TraceServiceImpl  --- onServiceKilled");
    }
}
